#!/bin/bash  
debug=0
input_file=$1
output_file="$2/event_codes.h"


output_dir=$(dirname "$output_file")
 
if [ ! -f "$output_file" ]; then
    mkdir -p "$output_dir"
    touch "$output_file"
    echo "$output_file 不存在，已创建路径和文件。"
else
    echo "$output_file 已存在。"
fi

current_time=$(date +"%Y-%m-%d %H:%M:%S")
echo "// ====================================================================" > $output_file
echo "// 这个是自动生成的文件，请勿修改" >> $output_file
echo "// 此文件的内容由特定工具或脚本自动生成" >> $output_file
echo "// 对此文件的任何手动更改都可能会在下次生成时被覆盖" >> $output_file
echo "// ====================================================================" >> $output_file

echo "// Create time:#$current_time " >> $output_file
echo "#ifndef EVENT_CODES_H" >> $output_file
echo "#define EVENT_CODES_H" >> $output_file

echo "#include <map>" >> $output_file
echo "#include <string>" >> $output_file
echo "class EventCodes {" >> $output_file
echo "public:" >> $output_file
echo "    static std::map<int, std::string> getEventCodes() {" >> $output_file
echo "        std::map<int, std::string> codes;" >> $output_file

# find event code from AGVEvent.msg
declare -A codes


if [ $debug -gt 0 ]; then
    echo "Enable debug message..."
fi

awk -v debug="$debug" '
BEGIN {
    in_section = 0;
    if (debug) print "Debug: BEGIN block executed" > "/dev/stderr"
}

/^# ecode id$/ {
    in_section = 1;
    if (debug) print "Debug: Entered section", $0 > "/dev/stderr"
    next;
}

in_section && /^########################################$/ {
    in_section = 0;
    if (debug) print "Debug: Exiting section at line", NR > "/dev/stderr"
    exit;
}

in_section && /^int16 / {
    if (debug) print "Debug: Processing int16 line:", $0 > "/dev/stderr"
    # 清理等号周围的空格
    gsub(/ *= */, "=")
    # 分割字段
    n = split($0, parts, /[= ]+/)
    if (parts[1] == "int16" && n >= 3) {
        code_name = parts[2]
        code_value = parts[3]
        codes[code_value] = "\"" code_name "\""
        if (debug) print "Debug: Added code", code_value, "=>", codes[code_value] > "/dev/stderr"
    }
}

END {
    if (debug) print "Debug: END block executed" > "/dev/stderr"
    for (key in codes) {
        trimmed_key = key
        gsub(/^[ \t\r\n]+|[ \t\r\n]+$/, "", trimmed_key)
        if (codes[key] != "" || trimmed_key != "") {
            print "        codes[" trimmed_key "] = " codes[key] ";"
        }
    }
}
' "$input_file" >> "$output_file"

echo "        return codes;" >> $output_file
echo "    }" >> $output_file
echo "};" >> $output_file
echo "#endif // EVENT_CODES_H" >> $output_file

echo  "$output_file generated."